package com.kkb.mybatis.framework.builder;

import com.kkb.mybatis.framework.sqlnode.*;
import com.kkb.mybatis.framework.sqlsource.DynamicSqlSource;
import com.kkb.mybatis.framework.sqlsource.RawSqlSource;
import com.kkb.mybatis.framework.sqlsource.SqlSource;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.Text;

import java.util.ArrayList;

/**
 *  解析sqlnode信息
 */
public class XMLScriptBuilder {

    private boolean isDynamic = false;

    public SqlSource parseScriptNode(Element element) {
        SqlNode mixedSqlNode = parseDynamicTags(element);
        SqlSource sqlSource;
        if (isDynamic) {
            //含有${}或动态标签
            sqlSource = new DynamicSqlSource(mixedSqlNode);
        } else {
            sqlSource = new RawSqlSource(mixedSqlNode);
        }
        return sqlSource;
    }

    private SqlNode parseDynamicTags(Element selecteElement) {

        //用于存储所有sqlNode节点
        ArrayList<SqlNode> sqlNodes = new ArrayList<>();

        //获取selectElement所有的子元素  包括所有文本节点和Element
        int count = selecteElement.nodeCount();

        for (int i = 0; i < count; i++) {

            Node node = selecteElement.node(i);

            if (node instanceof Text) {

                String text = node.getText();

                if (node == null) {
                    continue;
                }

                if ("".equals(text.trim())) {
                    continue;
                }

                TextSqlNode textSqlNode = new TextSqlNode(text.trim());
                //判断是否动态标签
                if (textSqlNode.isDynamic()) {
                    sqlNodes.add(textSqlNode);
                    isDynamic = true;
                } else {
                    sqlNodes.add(new StaticTextSqlNode(text.trim()));
                }
            } else if (node instanceof Element) {
                isDynamic = true;
                Element element = selecteElement;
                String name = element.getName();
                if ("if".equals(name)) {
                    String test = element.attributeValue("test");
                    // 递归  搞明白
                    SqlNode sqlNode = parseDynamicTags(element);
                    IfSqlNode ifSqlNode = new IfSqlNode(test, sqlNode);
                    sqlNodes.add(ifSqlNode);
                } else {
                    //todo
                }
            } else {
                //  todo
            }
        }

        return new MixedSqlNode(sqlNodes);
    }
}
